package shuashuami.hb.com.http;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import org.json.JSONException;
import org.json.JSONObject;

import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.manager.HbAppManager;
import shuashuami.hb.com.share.ShareCUserInfo;

/**
 * Created by hufangda on 2017/7/27.
 */

public class LoginHttp {

    private Activity activity;

    public LoginHttp(Activity activity) {
        this.activity = activity;
    }

    public void login() {
        HbAppManager.getInstance().SetClearableCookieJar(activity.getApplication());
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(activity);
        if (shareCUserInfo.getTag().equals("1")) {
            weiChartLogin();
        } else {
            loginUser();
        }
    }

    private void loginUser() {

        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {

                Message message = handler.obtainMessage(2);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(activity);
        HttpMethods.login(listener,
                shareCUserInfo.getPhoneNum(), shareCUserInfo.getPassword()
        );
    }

    private void weiChartLogin() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {

                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(activity);
        HttpMethods.weichartLogin(listener,
                shareCUserInfo.getwx_sn(), shareCUserInfo.getUserAvatar()
        );

    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 200) { //成功

                        } else {//初次登陆
                            ToastUtil.showShort(activity, jsonObject.getString("message"));
                        }
                    } catch (JSONException e) {
                        ToastUtil.showShort(activity, "数据解析错误");
                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

}
